using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using ProtoScratch.Common;

namespace ProtoScratch.Server
{
	public class ScratchServer : ScratchSession
	{
		private Thread listenThread;
		private TcpListener listenSocket;
		private bool aborted;
		
		private List<ServerConnection> Clients = new List<ServerConnection>();
		
		public ScratchServer (Type impl, int port) : base(impl)
		{
			this.port = port;
		}
		
		/// <summary>
		/// Start the server thread and listen for new connections.
		/// </summary>
		public void start()
		{
			lockSettings();
			if (listenThread != null)
				throw new ScratchException(ScratchException.eType.InvalidOperation, "ProtoScratch already started!");
			listenThread = new Thread(listenLoop);
			listenThread.Name = "Protoscratch Listener";
			listenThread.Start();
		}
		
		/// <summary>
		/// Stop the server.
		/// </summary>
		public void stop()
		{
			aborted = true;
			listenSocket.Stop();
		}
		
		/// <summary>
		/// This loop listens for new connections and handles them accordingly.
		/// </summary>
		private void listenLoop()
		{
			listenSocket = new TcpListener(IPAddress.Any, port);
			listenSocket.Start();
			
			while (!aborted)
			{
				var ThisClient = listenSocket.AcceptTcpClient();
				Clients.Add(new ServerConnection(this, ThisClient));
			}
		}
	}
}

